<template>
  <el-container class="login-container">
    <el-main>
      <el-card shadow="always">
        <el-form :model="loginForm" label-position="right" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="loginForm.username" :prefix-icon="User" clearable />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="loginForm.password" :prefix-icon="Key" type="password" clearable />
          </el-form-item>
          <el-form-item>
            <el-button @click="registerDialogShow = true">
              注册
            </el-button>
            <el-button type="primary" @click="handleLogin">
              登录
            </el-button>
          </el-form-item>
          <div style="clear: both;"></div>
        </el-form>
        <template #footer>
          温馨提示：请好好学习
        </template>
      </el-card>
    </el-main>
  </el-container>

  <el-dialog v-model="registerDialogShow" title="注册">
    <Register @register="handleDialogClose" />
    <template #footer>
      已有账号，前往 <el-button size="small" type="primary" @click="handleDialogClose">登录</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import { User, Key } from '@element-plus/icons-vue'
import { postLogin } from '@/api/userApi';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import Register from './Register.vue';

const router = useRouter()
const userStore = useUserStore()

const loginForm = ref({
  username: '',
  password: ''
})

const registerDialogShow = ref(false)

const handleLogin = () => {
  postLogin(loginForm.value).then(response => {
    if (response.status === 400) {
      ElMessage.error('用户名或者密码错误!')
    }
    if (response.status === 200) {
      ElMessage.success('登录成功')
      userStore.login(loginForm.value.username)
      router.push('/home')
    }
  }).catch(error => {
    console.error(error)
    ElMessage.error('登录失败')
  })
}

const handleDialogClose = () => {
  registerDialogShow.value = false
}
</script>

<style>
.el-card__footer {
  text-align: right;
  font-size: 12px;
}

.login-container {
  min-height: 84vh;
  background-image: url('https://jw.qvtu.edu.cn/css/images/login_icon.png');
  background-repeat: no-repeat;
  background-position: top 30% left 30%;
  position: relative;
}

.el-card {
  position: absolute;
  top: 30%;
  right: 10%;
  width: 400px;
}
</style>
